$(function () {
    bght_init();

    //**********按钮触发事件**********
    //新增按钮
    $("#bght_add").click(function () {
        bght_add('新增保供合同', 'add_bght');
    });
    //修改按钮
    $("#bght_tz").click(function () {
        bght_modify('修改保供合同', 'edit_bght');
    });
    //删除按钮
    $("#bght_del").click(function () {
        bght_delete();
    });
    $("#bght_agree").click(function () {
        bght_agree();
    });
    $("#bght_stop").click(function () {
        bght_stop();
    });
    //合同延期
    $("#bght_yq").click(function () {
        bght_htyq('合同延期', 'htyq_bght');
    });


//    $("#bght_tz").click(function () {
//        var row = $('#bght-grid').datagrid("getSelected");
//        if (row) {
//            var win = $.window({
//                title: '保供合同调整',
//                width: 1024,
//                height: 500,
//                cache: false,
//                url: $.webPath() + "/htgl/bghtgl/bghtgl_content?bghtId=" + row.id,
//                modal: true,
//                buttons: [
//                    {
//                        text: '保存',
//                        handler: function () {
//                            $(win).mask();
//                            bghtfkfs.grid.edatagrid("saveRow");
//                            $("#bghtglForm").form("submit", {
//                                onSubmit: function (param) {
//                                    var rows = bghtfkfs.grid.datagrid("getRows");
//                                    if (rows.length == 0) {
//                                        win.mask('hide');
//                                        $.messager.alert("提示", "付款方式没有维护！","warning");
//                                        return false;
//                                    }
//                                    if (!bghtfkfs.valid()) {
//                                        win.mask('hide');
//                                        $.messager.alert("提示", "付款比例必须等于100","warning");
//                                        return false;
//                                    }
//                                    for (var i = 0; i < rows.length; i++) {
//                                        param['bgfkfsList[' + i + '].fksj'] = rows[i].fksj;
//                                        param['bgfkfsList[' + i + '].fkbl'] = rows[i].fkbl;
//                                    }
//                                    return true;
//
//
//                                },
//                                success: function (data) {
//                                    win.mask('hide');
//                                    var obj = eval("(" + data + ")");
//                                    if (obj.statusCode == 200) {
//                                        $.messager.show({title: "提示", msg: '保存成功'});
//                                        win.window("close");
//                                    } else {
//                                        $.messager.alert("error", obj.message);
//                                    }
//                                }
//                            });
//                        }
//                    }
//                ]
//            });
//        }
//    });
})


function bght_htyq(title, action) {
    var record = $("#bght-grid").datagrid("getSelected");
    if (record == null) {
        $.messager.alert("提示", "请选择要延期的合同!", "warning");
        return;
    }
    var href = $.webPath() + "/htgl/bghtgl/bghtgl_yq?bghtId=" + record.id;
    var actionUrl = $.webPath() + "/htgl/bghtgl/" + action;
    bght_htyqDialog(title, href, actionUrl);
}

function bght_htyqDialog(title, href, actionUrl) {
    var win = $.window({
        title:title,
        width:420,
        height:400,
        cache:false,
        url:href,
        modal:true,
        buttons:[
            {
                text:'保存',
                handler:function () {
                    $(win).mask();
                    $('#form_bght_yq').form('submit', {
                        url:actionUrl,
                        onSubmit:function () {
                            var isValid = $(this).form('validate');
                            if (!isValid) {
                                $(win).mask('hide');
                                return false;
                            }
                            return isValid;
                        },
                        success:function (data) {
                            $(win).mask('hide');
                            var json = $.parseJSON(data);
                            if (json.statusCode == 200) {
                                $(win).window('close');
                                $('#bght-grid').datagrid('reload');
                                $.messager.show({
                                    title:'提示',
                                    msg:json.message,
                                    timeout:3000,
                                    showType:'slide'
                                });
                            } else
                                $.messager.alert('提示', json.message, 'error');
                        }
                    });
                }
            }
        ]
    });
}

function bght_delete() {
    var row = $('#bght-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('提示', '是否删除此保供合同？', function (r) {
            if (r) {
                var index = $('#bght-grid').datagrid('getRowIndex', row);
                $.post($.webPath() + '/htgl/bghtgl/delete_bght', {bghtId:row.id}, function (data) {
                    var obj = eval('(' + data + ')');
                    if (obj.statusCode == '200') {
                        $('#bght-grid').datagrid('deleteRow', index);
                        $('#bght-grid').datagrid('reload');
                        $('#bght_layout').layout('panel', 'center').panel('refresh');
                    } else
                        $.messager.alert('提示', obj.message, 'info');
                });
            }
        });
    } else {
        $.messager.alert('提示', "请选择要删除的保供合同", 'info');
    }
}

function bght_agree() {
    var row = $('#bght-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('提示', '合同履约后无法开单，是否履约此保供合同？', function (r) {
            if (r) {
                var index = $('#bght-grid').datagrid('getRowIndex', row);
                $.post($.webPath() + '/htgl/bghtgl/agree_bght', {bghtId:row.id}, function (data) {
                    var obj = eval('(' + data + ')');
                    if (obj.statusCode == '200') {
                        $('#bght-grid').datagrid('deleteRow', index);
                        $('#bght-grid').datagrid('reload');
                        $('#bght_layout').layout('panel', 'center').panel('refresh');
                    } else
                        $.messager.alert('提示', obj.message, 'info');
                });
            }
        });
    } else {
        $.messager.alert('提示', "请选择要履约的保供合同", 'info');
    }
}

function bght_stop() {
    var row = $('#bght-grid').datagrid('getSelected');
    if (row) {
        $.messager.confirm('提示', '合同终止后无法开单，是否终止此保供合同？', function (r) {
            if (r) {
                var index = $('#bght-grid').datagrid('getRowIndex', row);
                $.post($.webPath() + '/htgl/bghtgl/stop_cght', {bghtId:row.id}, function (data) {
                    var obj = eval('(' + data + ')');
                    if (obj.statusCode == '200') {
                        $('#bght-grid').datagrid('deleteRow', index);
                        $('#bght-grid').datagrid('reload');
                        $('#bght_layout').layout('panel', 'center').panel('refresh');
                    } else
                        $.messager.alert('提示', obj.message, 'info');
                });
            }
        });
    } else {
        $.messager.alert('提示', "请选择要终止的保供合同", 'info');
    }
}

//新增保供合同
function bght_add(title, action) {
    var href = $.webPath() + "/htgl/bghtgl/bghtgl_content";
    var actionUrl = $.webPath() + "/htgl/bghtgl/" + action;
    bght_showDialog(title, href, actionUrl);
}

//修改保供合同
function bght_modify(title, action) {
    var record = $("#bght-grid").datagrid("getSelected");
    if (record == null) {
        $.messager.alert("提示", "请选择要更新的记录!", "warning");
        return;
    }
    var href = $.webPath() + "/htgl/bghtgl/bghtgl_content?bghtId=" + record.id;
    var actionUrl = $.webPath() + "/htgl/bghtgl/" + action;
    bght_showDialog(title, href, actionUrl);
}

//弹出新增或修改的窗口
function bght_showDialog(title, href, actionUrl) {
    var win = $.window({
        title:title,
        iconCls:'icon-add2',
        width:1024,
        height:500,
        cache:false,
        url:href,
        modal:true,
        buttons:[
            {
                text:'保存',
                handler:function () {
                    $(win).mask();
                    $('#bghtglForm').form('submit', {
                        url:actionUrl,
                        onSubmit:function (param) {
                            bghtfkfs.grid.edatagrid("saveRow");
                            var record = bghtfkfs.grid.datagrid("getData");
                            if (!record.rows.length) {
                                $('#bghtglForm').tabs('select', "付款方式");
                                $.messager.alert("提示", "付款方式没有维护!", "waring");
                                $(win).mask('hide');
                                return false;
                            }
                            if (!bghtfkfs.valid()) {
                                $.messager.alert("提示", "付款比例必须等于100", "warning");
                                $(win).mask('hide');
                                return false;
                            }
                            //判断保供合同是否是导入的合同
                            if ($("[name='bght.sfdrbght']").val() != 'true') {
                                //结束编辑状态
                                $('#bght_mx').edatagrid("saveRow");
                                var r = $('#bght_mx').edatagrid("getSelected");
                                var index = $('#bght_mx').edatagrid("getRowIndex", r);
                                $('#bght_mx').edatagrid("endEdit", index);
                                $('#bght_mx').datagrid('acceptChanges');
                            }

                            var isValid = $(this).form('validate');
                            if (!isValid) {
                                $(win).mask('hide');
                                return false;
                            }
                            var data;

                            if ($("[name='bght.sfdrbght']").val() != 'true') {
                                data = $('#bght_mx').edatagrid("getData");
                            } else {
                                data = $('#bght_mx_dr').edatagrid("getData");
                            }

                            var arrayPrefix = 'bght.htmxList';
                            var fkfsPrefix = "bght.bgFkfs";
                            var paramString = "{";
                            for (var i = 0; i < record.rows.length; i++) {
                                {
                                    var objectString = $.toJSONStringSubPrefix(record.rows[i], fkfsPrefix + "[" + i + "].", [
                                        'fksj',
                                        'fkbl'
                                    ]);
                                    paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
                                }
                            }
                            for (var i = 0; i < data.rows.length; i++) {
                                if ($("[name='bght.sfdrbght']").val() != 'true') {
                                    if (data.rows[i].sbsl == 0 || data.rows[i].sbsl == null) {
                                        $('#bghtglForm').tabs('select', "合同明细");
                                        $.messager.alert('提示', '第' + (i + 1) + '行的数量不能为0 !', 'info');
                                        $(win).mask('hide');
                                        return false;
                                    } else if (data.rows[i].hsj == 0 || data.rows[i].hsj == null) {
                                        $('#bghtglForm').tabs('select', "合同明细");
                                        $.messager.alert('提示', '第' + (i + 1) + '行的含税价不能为0 !', 'info');
                                        $(win).mask('hide');
                                        return false;
                                    } else if (data.rows[i].bhsj == 0 || data.rows[i].bhsj == null) {
                                        $('#bghtglForm').tabs('select', "合同明细");
                                        $.messager.alert('提示', '第' + (i + 1) + '行的不含税价不能为0 !', 'info');
                                        $(win).mask('hide');
                                        return false;
                                    } else if (data.rows[i]['cd.id'] == null || data.rows[i]['cd.id'] == '') {
                                        $('#bghtglForm').tabs('select', "合同明细");
                                        $.messager.alert('提示', '第' + (i + 1) + '行的产地不能为空 !', 'info');
                                        $(win).mask('hide');
                                        return false;
                                    }
                                }

                                var objectString = $.toJSONStringPrefix(data.rows[i], arrayPrefix + "[" + i + "].");
                                paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
                            }
                            if (data.rows && data.rows.length > 0)
                                paramString = paramString.substring(0, paramString.length - 1);
                            paramString += "}";
                            $.extend(param, $.parseJSON(paramString));
                            return isValid;
                        },
                        success:function (data) {
                            $(win).mask('hide');
                            var json = $.parseJSON(data);
                            if (json.statusCode == 200) {
                                $(win).window('close');
                                $('#bght-grid').datagrid('reload');
                                $.messager.show({
                                    title:'提示',
                                    msg:json.message,
                                    timeout:3000,
                                    showType:'slide'
                                });
                            } else
                                $.messager.alert('提示', json.message, 'error');
                        }
                    });
                }
            }
        ]
    });
}

function bght_init() {
    //采购方公司加载
    $("[name='bght_ssgs']").jgbmtree($("[name='bght_ssbm']"), $("[name='bght_cjr']"), '', '')
    //合作方加载
    $("[name='bght_gys']").qyjgzcombobox();
    var options = getBghtGridOption("");
    $('#bght-grid').datagrid(options);
}

function bght_search() {
    var zt = $("#bght-toolbar input[name='bght_zt']").val();
    var type = $("#bght-toolbar input[name='bght_type']").val();
    var htbh = $("#bght-toolbar input[name='bght_htbh']").val();
    var gys = $("#bght-toolbar input[name='bght_gys']").val();
    var ssgs = $("#bght-toolbar input[name='bght_ssgs']").val();
    var ssbm = $("#bght-toolbar input[name='bght_ssbm']").val();
    var jhr = $("#bght-toolbar input[name='bght_cjr']").val();
    var startDate = $("#bght-toolbar [name='bght_startDate']").val();
    var endDate = $("#bght-toolbar [name='bght_endDate']").val();
    var qdr = $("#bght-toolbar input[name='bght_qdr']").val();
    var wzbm = $("#bght-toolbar [name='wzbm']").val();
    var options = $.extend(getBghtGridOption(type),
        {queryParams:{wzbm:wzbm, zt:zt, cglx:type, htbh:htbh, hzfId:gys, ssgsId:ssgs, ssbmId:ssbm, jhrId:jhr, qdr:qdr, startDate:startDate, endDate:endDate}});
    $('#bght-grid').datagrid(options);
}

function getBghtGridOption() {
    var options = {
        url:$.webPath() + "/htgl/bghtgl/bghtList",
        toolbar:"#bght-toolbar",
        fitColumns:true,
        singleSelect:true,
        pagination:true,
        fit:true,
        pageNumber:1,
        rownumbers:true,
        onLoadSuccess:function () {
            $(this).datagrid('selectRow', 0);

            $(".datagrid-htable .datagrid-cell").css('text-align', 'center');
        },
        loadFilter:function (data) {
            $.each(data.rows, function () {
                if (this.zt) {
                    this.zt = this.zt == 'ysp' ? "已审批" : this.zt == 'yly' ? "已完结" : this.zt == 'yzz' ? "已终止" : this.zt == 'ytj' ? "已提交" : "已保存";
                }
            })
            if (!this.wlyl)
                this.wlyl = 0;
            this.wlyl = this.sbsl - this.wlyl;
            return data;
        },
        onSelect:function (rowIndex, rowData) {
            if (!rowData) {
                $("#bght_add").css('display', 'none');
                $("#bght_tz").css('display', 'none');
                $("#bght_del").css('display', 'none');
                $("#bght_sh").css('display', 'none');
                $('#bght_agree').css('display', 'none');
                $('#bght_stop').css('display', 'none');
                $('#bght_layout').layout('remove', 'center');
                return;
            }
            if (rowData && rowData.zt == '已保存') {
                $("#bght_tz").css('display', '');
                $("#bght_del").css('display', '');
                $("#bght_sh").css('display', '');
                $('#bght_agree').css('display', 'none');
                $('#bght_stop').css('display', 'none');
            } else if (rowData && rowData.zt == '已审批') {
                $("#bght_tz").css('display', 'none');
                $("#bght_del").css('display', 'none');
                $("#bght_sh").css('display', 'none');
                $('#bght_agree').css('display', '');
                $('#bght_stop').css('display', '');
            } else {
                $("#bght_tz").css('display', 'none');
                $("#bght_del").css('display', 'none');
                $("#bght_sh").css('display', 'none');
                $('#bght_agree').css('display', 'none');
                $('#bght_stop').css('display', 'none');
            }
        }
    };
    var columns = {columns:[
        [
            {field:'htbm', title:'合同号', align:'center', width:113, formatter:bghtCell},
            {field:'hzf_qc', title:'供应商', align:'center', width:178},
            {field:'sbsl', title:'数量', align:'right', formatter:function (value) {
                var sl = formatSlForHtml(value, ",");
                return sl;
            }, width:142},
            {field:'wlyl', title:'未履约量', align:'right',
                formatter:function (value) {
                    var sl = formatSlForHtml(value, ",");
                    return sl;
                }, width:123},
            {field:'sbgs_qc', title:'申报公司', align:'center', width:151},
            {field:'sbbm_qc', title:'申报部门', align:'center', width:94},
            {field:'htqdr', title:'签订人', align:'center', width:47},
            {field:'qdrq', title:'签订日期', align:'center', width:123},
            {field:'jsrq', title:'结束日期', align:'center', width:86},
            {field:'zt', title:'状态', width:52, align:'center', formatter:formatBghtSp}
        ]
    ]}
    options = $.extend(options, columns);
    return options;
}

function formatBghtSp(val, row) {
    if (row.zt == "已保存" || row.zt == "已完结" || row.zt == "已终止") {
        return val;
    } else {
        return '<a href="javascript:void(0);" style="color: red">' + val + '</a>';
    }
}

// 审核合同
$("#bght_sh").click(function () {
    var record = $('#bght-grid').datagrid("getSelected");
    if (record == null) {
        $.messager.alert("提示", "请选择要提交的保供合同!", "info");
        return;
    }
    if (record.htwb_id) {
        $.messager.confirm("提示", "是否审核该保供合同?", function (r) {
            if (r) {
                $.ajax({
                    type:"POST",
                    url:$.webPath() + "/htgl/bghtgl/checkBght",
                    dataType:"json",
                    data:{bghtId:record.id},
                    beforeSend:function () {
                        $.messager.progress();
                    },
                    success:function (data) {
                        $.messager.progress("close");
                        if (data.statusCode == 300)
                            $.messager.alert("提示", data.message, "error");
                        if (data.statusCode == 200) {
                            $.messager.show({title:"提示", msg:"保供合同审核成功！"});
                            $('#bght-grid').datagrid('reload', {
                            });
                        }
                    }
                });
            }
        });
    } else {
        $.messager.confirm("提示", "该合同文本未编辑,是否编辑合同文本?", function (r) {
            if (r) {
                bght_modify('修改保供合同', 'edit_bght');
            } else {
                $.ajax({
                    type:"POST",
                    url:$.webPath() + "/htgl/bghtgl/checkBght",
                    dataType:"json",
                    data:{bghtId:record.id},
                    beforeSend:function () {
                        $.messager.progress();
                    },
                    success:function (data) {
                        $.messager.progress("close");
                        if (data.statusCode == 300)
                            $.messager.alert("提示", data.message, "error");
                        if (data.statusCode == 200) {
                            $.messager.show({title:"提示", msg:"保供合同审核成功！"});
                            $('#bght-grid').datagrid('reload', {
                            });
                        }
                    }
                });
            }
        });
    }
});



